/**
 * 登录功能，实现了接口功能，记住密码，自动登录功能
 * @author 黄广星
 */
package com.taxsystem.huangguangxing.login;


import java.util.concurrent.ExecutionException;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.ActionBar;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.Toast;

import com.main.taxsystem.R;
import com.taxsystem.main.MainTabActivity;
import com.taxsystem.tool.CommonOperations;
import com.taxsystem.tool.HttpUtil;

public class LoginActivity extends Activity {

	private static final String ACTION = "com.taxsystem.huangguangxing.login.HTTP_GET_RESPONSE";

	private String url = "http://itaxmanager.duapp.com/app/user/validate?";

	private SharedPreferences spLogin;
	private EditText userName, password;
	private CheckBox rememberPassword;//autoLogin;
	private Button login, resign;
	private String userNameValue, passwordValue;

	private LocalBroadcastManager lbm;
	private MyThread myThread;

	User user;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.login_layout_hgx);
		
		ActionBar actionBar = getActionBar();  
		actionBar.hide();  

		// 获得实例对象
		spLogin = this.getSharedPreferences("userInfo", Context.MODE_PRIVATE);
		userName = (EditText) findViewById(R.id.user_name);
		password = (EditText) findViewById(R.id.user_password);
		rememberPassword = (CheckBox) findViewById(R.id.remember_password);
//		autoLogin = (CheckBox) findViewById(R.id.auto_login_check);
		login = (Button) findViewById(R.id.login);
		resign = (Button) findViewById(R.id.resign);
		registerBroadcastReceiver();

		userName.setText(spLogin.getString("USER_NAME", ""));
		// 判断记住密码多选框的状态
		if (spLogin.getBoolean("ISCHECK", false)) {
			// 设置默认是记录密码状态
			rememberPassword.setChecked(true);
			password.setText(spLogin.getString("PASSWORD", ""));
			// 判断自动登陆多选框状态
//			if (spLogin.getBoolean("AUTO_ISCHECK", false)) {
//				// 设置默认是自动登录状态
//				autoLogin.setChecked(true);
//
//				Toast.makeText(LoginActivity.this, "自动登录成功", Toast.LENGTH_SHORT)
//						.show();
//				user.setUserId(spLogin.getInt("USER_ID",0));
//				user.setUserCode(spLogin.getString("USER_CODE",""));
//				user.setUserName(spLogin.getString("USER_NAME",""));
//				user.setPassword(spLogin.getString("PASSWORD",""));
//				user.setType(spLogin.getInt("TYPE",0));
//				user.setState(spLogin.getInt("STATE",0));
//				user.setLoginTime(spLogin.getString("LOGIN_TIME",""));
//				LoginMassege.setLogin(true, user);
//				Intent intent2=new Intent();
//				intent2.setClass(LoginActivity.this,MainTabActivity.class);
//				finish();
//
//			}
		}

		login.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {

				if(isOK())
				{
					url = url + "usercode=" + userNameValue + "&password="
						+ passwordValue;

					visitNetwork();// 访问网络
				}
			}
		});

		// 监听记住密码多选框按钮事件
		rememberPassword
				.setOnCheckedChangeListener(new OnCheckedChangeListener() {
					public void onCheckedChanged(CompoundButton buttonView,
							boolean isChecked) {
						if (rememberPassword.isChecked()) {
							spLogin.edit().putBoolean("ISCHECK", true).commit();

						} else {
							spLogin.edit().putBoolean("ISCHECK", false)
									.commit();

						}

					}
				});

//		// 监听自动登录多选框事件
//		autoLogin.setOnCheckedChangeListener(new OnCheckedChangeListener() {
//			public void onCheckedChanged(CompoundButton buttonView,
//					boolean isChecked) {
//				if (autoLogin.isChecked()) {
//					spLogin.edit().putBoolean("AUTO_ISCHECK", true).commit();
//
//				} else {
//					spLogin.edit().putBoolean("AUTO_ISCHECK", false).commit();
//				}
//			}
//		});


		resign.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent();
				/* 指定intent要启动的类 */
				intent.setClass(LoginActivity.this, ResignActivity.class);
				/* 启动一个新的Activity */
				startActivity(intent);
			}
		});
	}// onCreate

	void visitNetwork() {
		if (CommonOperations.isNetworkConnected(this)) {
			myThread = new MyThread();
			myThread.run();
		} else
			Log.w("tag1", "device can't connect network");
	}

	void registerBroadcastReceiver() {
		lbm = LocalBroadcastManager.getInstance(this);
		IntentFilter filter = new IntentFilter(ACTION);
		BroadcastReceiver myRecive = new MyRecive();
		lbm.registerReceiver(myRecive, filter);
	}

	private class MyThread extends Thread {
		@Override
		public void run() {

			Intent intent = new Intent(ACTION);
			try {
				String result = HttpUtil.getRequest(url);
				intent.putExtra("JSON", result);
				lbm.sendBroadcast(intent);
			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (ExecutionException e) {
				e.printStackTrace();
			}
		}
	}

	private class MyRecive extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {

			String jsonString = intent.getStringExtra("JSON");

			if (jsonString == null) {

				Log.e("tag1", "MyRecive.onReceive():jsonString is null");
				return;
			}

			try {

				JSONObject jsonObject = new JSONObject(jsonString);
				int isLogin = jsonObject.getInt("code");
				@SuppressWarnings("unused")
				String loginMessage = jsonObject.getString("message");
				// JSONObject objectUser = new JSONObject("data");//有问题
				JSONObject objectUser = new JSONObject(
						jsonObject.getString("data"));// 有问题
				user = new User();

				user.setUserId(objectUser.getInt("userId"));
				user.setUserCode(objectUser.getString("userCode"));
				user.setUserName(objectUser.getString("userName"));
				user.setPassword(objectUser.getString("password"));
				user.setType(objectUser.getInt("type"));
				user.setState(objectUser.getInt("state"));
				user.setLoginTime(objectUser.getString("loginTime"));
				
				if (isLogin == 1) {
					Toast.makeText(LoginActivity.this, "登录成功",
							Toast.LENGTH_SHORT).show();
					LoginMassege.setLogin(true, user);

					if (rememberPassword.isChecked()) {
						// 记住用户名、密码、
						Editor editor = spLogin.edit();
						editor.putString("USER_NAME", userNameValue);
						editor.putString("PASSWORD", passwordValue);
						editor.putInt("USER_ID",objectUser.getInt("userId"));
						editor.putString("USER_CODE",objectUser.getString("userCode"));
						editor.putString("USER_NAME",objectUser.getString("userName"));
						editor.putString("PASSWORD",objectUser.getString("password"));
						editor.putInt("TYPE",objectUser.getInt("type"));
						editor.putInt("STATE",objectUser.getInt("state"));
						editor.putString("LOGIN_TIME",objectUser.getString("loginTime"));
						editor.commit();
					}
				} else {

					Toast.makeText(LoginActivity.this, "用户名或密码错误，请重新登录",
							Toast.LENGTH_LONG).show();
				}
				Intent intent2=new Intent();
				intent2.setClass(LoginActivity.this,MainTabActivity.class);
				startActivity(intent2);
				finish();
			} catch (JSONException e) {
				e.printStackTrace();
			} finally {

			}
		}
	}
	
	// 判断输入信息是否合法
		private boolean isOK() {
			boolean flag = false;
			userNameValue = userName.getText().toString();
			passwordValue = password.getText().toString();
			if("".equals(userNameValue))
				Toast.makeText(LoginActivity.this, "用户名不能为空",
						Toast.LENGTH_LONG).show();	
			else if("".equals(passwordValue))
				Toast.makeText(LoginActivity.this, "密码不能为空",
						Toast.LENGTH_LONG).show();
			else
				flag = true;
			return flag;
		}
}
